#!/bin/sh

if [ -z "$3" ]; then
    echo "usage: check_galaxy <server> <username> <password> <handler>"
    exit 3
fi

# not sure why this is necessary, but nagios' $HOME is /root, despite not running as root.
HOME=/var/lib/nagios
export HOME

here=`dirname $0`
host=`basename $1`
handler="$4"
var="$HOME/.check_galaxy/$host/$handler"

mkdir -p $var
touch $var/iterations
iterations=`cat $var/iterations`
if [ -z "$iterations" ]; then
    iterations=0
fi

new_history=''
if [ $iterations -gt 64 ]; then
    new_history='-n'
    echo 0 > $var/iterations
else
    echo `expr $iterations + 1` > $var/iterations
fi

date >> $var/log
status=`python $here/check_galaxy.py $new_history $1 $2 $3 $4 2>&1 | tee -a $var/log | tail -n 1`

echo "$status"

case "$status" in
    "OK: "*)
        exit 0
        ;;
    "AssertionError: "*)
        exit 1
        ;;
    *)
        exit 2
        ;;
esac
